package com.itcodai.controller.course12;

import com.itcodai.entity.User;
import com.itcodai.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author c-fanqj
 * @date 2023/4/5
 * @apiNote 监听器测试
 */
@RestController
@RequestMapping("/listener")
@Api(value = "监听器基本操作")
public class TestListenerController {

    @Resource
    private UserService userService;

    // 监听Servlet上下文对象：初始化数据，用于缓存 【首页数据】
    // application 这种是缓存在内存中，对内存会有消耗
    @GetMapping("/user")
    @ApiOperation(value = "监听Servlet上下文对象")
    public User getUser(HttpServletRequest request) {
        ServletContext application = request.getServletContext();
        return (User) application.getAttribute("user");
    }

    // 监听HTTP会话 Session对象 【获取在线用户数量】
    // 获取当前在线人数，该方法有bug
    @GetMapping("/total")
    @ApiOperation(value = "监听HTTP会话Session对象")
    public String getTotalUser(HttpServletRequest request) {
        Integer count = (Integer) request.getSession()
                .getServletContext().getAttribute("count");
        return "当前在线人数：" + count;
    }

    @GetMapping("/total2")  // 推荐
    @ApiOperation(value = "监听HTTP会话Session对象2")
    public String getTotalUser(HttpServletRequest request,
                               HttpServletResponse response) {
        Cookie cookie;
        try {
            // 把sessionId记录在浏览器中
            cookie = new Cookie("JSESSIONID",
                    URLEncoder.encode(request.getSession().getId(), "utf-8"));
            cookie.setPath("/");
            // 设置cookie有效期为2天，设置长一点
            cookie.setMaxAge(48*60*60); // s
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Integer count = (Integer) request.getSession()
                .getServletContext().getAttribute("count");
        return "当前在线人数：" + count;
    }

    // 监听客户端请求Servlet Request对象
    @GetMapping("/request")
    @ApiOperation(value = "监听客户端请求Servlet Request对象")
    public String getRequestInfo(HttpServletRequest request) {
        //System.out.println("requestListener中的初始化的name数据：" +
        //        request.getAttribute("name"));
        return "requestListener中的初始化的name数据：" +
                request.getAttribute("name");
        //return "success";
    }

    @GetMapping("/publish")
    @ApiOperation(value = "自定义事件监听")
    public User publishEvent() {
        return userService.getUser2();
    }

}
